import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { ElMessageBox } from 'element-plus'
import { resetRouter } from '@/router'

let base_url = ''
// create an axios instance
const service = axios.create({
  baseURL: base_url // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // 与后端约定通过在header里的Authorization = 'Token '+getToken()
      config.headers['Authorization'] = 'Token ' + getToken()
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    // window.console.log(res)
    if (typeof res === 'string' && res.split(',')[0] == 401) {
      ElMessageBox.alert(res.split(',')[1], '警告', {
        confirmButtonText: '确定',
        type: 'error',
        showClose: false
      }).then(() => {
        store.dispatch('user/resetToken')
        resetRouter()
      })
    }
    return res
  },
  (error) => {
    // console.log(error) // for debug
    // ElMessage({
    //   message: error.message,
    //   type: 'error',
    //   duration: 2000
    // })
    return Promise.reject(error)
  }
)

export default service
